package main

import "os"
import "fmt"

import "panel"
import "edit"
import "header"
import "frame"

import "exp/draw"
import "exp/draw/x11"

func main() {
	c, err := x11.NewWindow()
    if err != nil {
        fmt.Printf("cannot connect: %v\n", err)
        os.Exit(1)
    }
    loop(c)
}

type ignore int

func (ignore) Do(command string) {}

func loop(win draw.Window) {
    cols := 100
    rows := 20
//
    c := &panel.ScrollablePanel{}
    h := header.NewHeaderPanel(nil, nil)
    e := edit.NewEditCompilePanel(c, h)
    h.Other = e.Edit
    h.Do = e.Edit
    f := frame.NewFrame(e.Edit, e, c, h)
    s := panel.NewShelf(f, frame.NewFrame(ignore(0), edit.NewEditCompilePanel(nil, nil), nil, nil))
    wp := panel.NewWindowPanel(win,s)
    wp.Resize(rows, cols, 0, 0)
    wp.Refresh()
//
    var focus panel.Type = e.Edit
    events := win.EventChan()
    control_pressed := false
    for {
    	e := <-events
    	if e == nil { break }
    	switch event := e.(type) {
    	
    	case draw.KeyEvent:
    		k := event.Key
    		fmt.Println("Key event: ", k)
    		switch k {
    		case 65507: // CTRL pressed
    			control_pressed = true
    			
    		case -65507: // CTRL released
    			control_pressed = false
    			
    		default:
	    		if k > 0 {
	    			if control_pressed { k = k - 'a' + 1 }
	    			newFocus := focus.Key(k) // keys.KeyCodeToChar(&event))
	    			if newFocus != nil { focus = newFocus }
	    		}
    		}
    		
    	case draw.MouseEvent:
    		// IGNORE for now.
    		
    	default:
	    	fmt.Printf(">> event %T %v\n", e, e)
    	// case x11.KeyReleaseEvent:
    	//	newFocus := focus.Key(keys.KeyCodeToChar(&event))
    	//	if newFocus != nil { focus = newFocus }
    		
    	// case x11.ExposeEvent:
    	// 	wp.Refresh()		
    	// col, line, _ := curses.MouseEvent()
        //    focus = wp.FocusForClick(line, col)
        }
        focus.Focus()
        win.FlushImage()
        // w.Refresh()
        // if inp == 'q' - 'a' + 1 { break }
        // if inp == 'x' - 'a' + 1 { wp.Refresh(); focus.Focus() 
    }
}



